#include "spellchecker.h"
#include "ui_spellchecker.h"

SpellChecker::SpellChecker (QWidget *parent) :
	QDialog(parent),
	ui(new Ui::SpellChecker)
{
	ui->setupUi(this);

	m_badIndex = 0;
	m_text.clear ();
	m_ortho = new Ortho (this);

	loadLanguages ();

	connect (ui->close,
			 SIGNAL(clicked()),
			 this,
			 SLOT(close()));

	connect (ui->replaceAll,
			 SIGNAL(clicked()),
			 this,
			 SLOT(onReplaceAllClicked()));

	connect (ui->unknownCombo,
			 SIGNAL(currentIndexChanged(QString)),
			 this,
			 SLOT(onUnknownComboIndexChanged(QString)));


	connect (ui->languages,
			 SIGNAL(currentIndexChanged(QString)),
			 this,
			 SLOT(onLanguagesCurrentIndexChange(QString)));

	connect (ui->suggestList,
			 SIGNAL(currentTextChanged(QString)),
			 this,
			 SLOT(onSuggestListCurrentTextChanged(QString)));

	connect (ui->wordEdit,
			 SIGNAL(textChanged(QString)),
			 this,
			 SLOT(onWordEditTextChanged(QString)));

}
//---------------------------------
void SpellChecker::loadLanguages ()
{
	ui->languages->clear ();
	ui->languages->addItems (m_ortho->languages ());
	ui->languages->setCurrentIndex (ui->languages->findText (m_ortho->currentLanguage ()));
}

//----------------------------
SpellChecker::~SpellChecker()
{
	delete ui;
}
//---------------------------------------
void SpellChecker::onReplaceAllClicked ()
{
}
//-----------------------------------------------------------
void SpellChecker::onUnknownComboIndexChanged(QString newWord)
{
	ui->wordEdit->setText (newWord);
	ui->wordEdit->selectAll ();
	ui->wordEdit->setFocus ();

	QStringList suggestions = m_ortho->suggests (newWord);
	ui->suggestList->clear ();
	ui->suggestList->addItems (suggestions);
}
//-----------------------------------------
int SpellChecker::run (const QString &text)
{
	m_text = text;

	updateDialog ();

	return exec ();
}
//------------------------------
void SpellChecker::updateDialog ()
{
	QStringList badWords (m_ortho->unknownWords (m_text));
	ui->unknownCombo->clear ();
	ui->unknownCombo->addItems (badWords);
	ui->unknownCombo->setCurrentIndex (0);
}
//-----------------------------------------------------------
void SpellChecker::onLanguagesCurrentIndexChange(QString lang)
{
	m_ortho->setCurrentLanguage (lang);
	updateDialog ();

}
//--------------------------------------------------------
void SpellChecker::onWordEditTextChanged (QString newWord)
{
	if (newWord.isEmpty () || newWord == ui->unknownCombo->currentText ())
	{
		ui->replaceAll->setDisabled (true);
		ui->ignore->setDisabled (true);
	}
	else
	{
		ui->replaceAll->setEnabled (true);
		ui->ignore->setEnabled (true);
	}
}
//------------------------------------------------------------------
void SpellChecker::onSuggestListCurrentTextChanged(QString newWord)
{
	if (! newWord.isEmpty ())
	{
		ui->wordEdit->setText (newWord);
		ui->wordEdit->selectAll ();
		ui->wordEdit->setFocus ();
	}
}
